import React, { FC, useState, useEffect, useRef } from 'react'
import { message, Tabs, Modal, Form, Input, Select, Button } from 'antd'

import TopHeader, { ListTitle } from '~/components/top-header'
import WaitingList from './container/waiting-list'
import { useNavigate, useLocation } from 'react-router-dom'
import { AttachmentClassificationMap } from '~/constants'
import { AttachmentDeletion, viewAttachmentList, getAttachHttpUrl, UpdatingFiles } from '~/api/query-api'
import UploadCom, { putObject } from '~/components/my-upload'
import { queryPictureNameList, queryPictures } from '~/api/upload-item-api'

const { TabPane } = Tabs
const { Option } = Select
const selectMap = new Map()
const wechatImg = new Map([])

const PropertyInvolved: FC = () => {
  const [form] = Form.useForm()
  const [isShowClassificationModal, setIsShowClassificationModal] = useState(false)
  const recordData = useRef({ storeId: '', fileName: '', caseNo: '', caseName: '' })
  const [isShowDeleteReason, setIsShowDeleteReason] = useState(false)
  const [waitCastItems, setWaitCastItems] = useState([])
  const [setCertificateVisible] = useState(false)
  const [isShowWechatUpload, setIsShowWechatUpload] = useState(false)
  const [imgLists, setImgLists] = useState([])
  const navigate = useNavigate()
  const { state, pathname }: any = useLocation()
  const [isShowUpload, setIsShowUpload] = useState(false)
  const [selectImgLists, setSelectImgLists] = useState<any>([])

  const { caseCompanyName, caseDepartmentName, caseName, caseNo, activeKey = '1', isShowAddFiles } = state || {
    activeKey: '1'
  }

  const localImg: any = new Map([])

  const handleUplodaImg = async () => {
    const value = form.getFieldValue('classification')
    const localImgValues: any[] = [...localImg.values()]
    await UpdatingFiles({
      caseNo: caseNo,
      caseName: caseName,
      fileCategory: value ,
      fileSource: 'local',
      storeAttach: localImgValues.map(item => {
        return {
          fileName: item.name,
          storeId: item.storeId
        }
      })
    })
    handleGetueryWaitCastItems()
  }

  const handleGetPictureNameList = async () => {
    const { data } = await queryPictureNameList()
    const res = await queryPictures(data)
    setImgLists(res.data)
  }

  const handleGetueryWaitCastItems = async () => {
    const value = form.getFieldValue('classification')
    const { data } = await viewAttachmentList({
      caseNo,
      fileCategory: value
    })
    setWaitCastItems(data)
  }

  useEffect(() => {
    handleGetueryWaitCastItems()
    handleGetPictureNameList()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  const headData = [
    {
      childen: [
        {
          label: '案件编号:',
          value: caseNo
        },
        { label: '案件名称:', value: caseName }
      ]
    },
    {
      childen: [
        { label: '办案单位:', value: caseCompanyName },
        { label: '办案部门:', value: caseDepartmentName }
      ]
    }
  ]

  const onClickDownLoadFile = async (record: any) => {
    const { data } = await getAttachHttpUrl({ storeId: record.storeId })
    window.open(data)
    // const image = new Image()
    // // 解决跨域 Canvas 污染问题
    // image.setAttribute('crossOrigin', 'anonymous')
    // image.onload = function() {
    //   const canvas = document.createElement('canvas')
    //   canvas.width = image.width
    //   canvas.height = image.height
    //
    //   const context = canvas.getContext('2d')
    //   context!.drawImage(image, 0, 0, image.width, image.height)
    //   const url = canvas.toDataURL('image/png')
    //
    //   // 生成一个a元素
    //   const a = document.createElement('a')
    //   // 创建一个单击事件
    //   const event = new MouseEvent('click')
    //
    //   // 将a的download属性设置为我们想要下载的图片名称，若name不存在则使用‘下载图片名称’作为默认名称
    //   a.download = record.fileName || '下载图片名称'
    //   // 将生成的URL设置为a.href属性
    //   a.href = url
    //   // 触发a的单击事件
    //   a.dispatchEvent(event)
    // }
    // alert(data)
    // image.src = data
  }

  const onClickDeleteReason = async () => {
    const data = await AttachmentDeletion({
      storeId: recordData.current.storeId,
      deleteReason: form.getFieldValue('deleteReason')
    })
    if (data.error) {
      setIsShowDeleteReason(false)
      form.resetFields(['deleteReason'])
      return
    }
    message.success(`删除${recordData.current.fileName}成功`)
    handleGetueryWaitCastItems()
    setIsShowDeleteReason(false)
    form.resetFields(['deleteReason'])
  }

  const onClickAddAttachmentList = (record: any) => {
    recordData.current = record
    setIsShowClassificationModal(true)
  }

  const onClickSaveSetting = async () => {
    handleGetueryWaitCastItems()
    setIsShowClassificationModal(false)
    setIsShowUpload(true)
    // setIsSwitchAttachmentList(true)
    // handleSwitchList(false)
  }

  //base64转blob
  const dataURLtoFile = (dataurl: string) => {
    const arr = `data:image/png;base64,${dataurl}`.split(',')
    const mime = arr[0].match(/:(.*?);/)![1]
    const bstr = atob(arr[1])
    let n = bstr.length
    const u8arr = new Uint8Array(n)
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n)
    }
    const blob = new File([u8arr], 'file', { type: mime })
    return blob
  }

  const onClickImg = async (index: number) => {
    const dataurl: any = imgLists[index]
    const files = dataURLtoFile(dataurl)
    selectMap.set(index, !selectMap.get(index))
    const isSelected = selectMap.get(index)
    if (isSelected) {
      const data = await putObject({ files, frontend: '' })
      wechatImg.set(dataurl, { storeId: data.storeId, name: files.name })
    } else {
      wechatImg.delete(dataurl)
    }
    setSelectImgLists([...selectImgLists, dataurl])
  }

  const onClickAssociatedPicture = async () => {
    const value = form.getFieldValue('classification')
    const wechatImgValues: any[] = [...wechatImg.values()]
    const data = await UpdatingFiles({
      caseNo: caseNo,
      caseName: caseName,
      fileCategory: value,
      storeAttach: [...wechatImgValues].map(item => {
        return {
          fileName: `从政务微信上传 ${new Date().getTime()}`,
          storeId: item.storeId
        }
      }),
      fileSource: 'wechat'
    })
    if (data.error) {
      setIsShowWechatUpload(false)
      return
    }
    handleGetueryWaitCastItems()
    setIsShowWechatUpload(false)
    message.success('政务微信上传成功')
  }

  return (
    <div>
      <TopHeader headData={headData} />
      <ListTitle title="附件列表" />
      <div style={{ display: 'flex', marginTop: 20 }}>
        {isShowAddFiles && (
          <Button type="primary" onClick={onClickAddAttachmentList} style={{ marginLeft: 20 }}>
            添加附件
          </Button>
        )}
        {isShowUpload && (
          <div style={{ display: 'flex', marginLeft: 10, alignItems: 'center' }}>
            <UploadCom
              frontend=""
              onSuccess={async ({ storeId, name, imgUrl, files }: any) => {
                localImg.set(name, { storeId, name: files.name, imgUrl })
                await handleUplodaImg()
                message.success('上传图片成功')
              }}
              onRemove={() => {
                localImg.clear()
              }}
              showUploadList={false}
              title="从本地上传"
            />
            <Button
              style={{ marginLeft: 10 }}
              onClick={() => {
                setIsShowWechatUpload(true)
              }}
            >
              从政务微信上传
            </Button>

            <div style={{ marginLeft: 10, color: 'red' }}>目前仅支持 png jpeg docx pdf 类型的文件</div>
          </div>
        )}
      </div>
      <main style={{ marginTop: 21 }}>
        <Tabs
          activeKey={activeKey}
          onChange={(activeKey: string) => {
            navigate(pathname, { replace: true, state: { ...state, activeKey } })
          }}
        >
          <TabPane tab={<span>附件列表</span>} key="1">
            <WaitingList
              onClickDownLoadFile={onClickDownLoadFile}
              onClickDeleteReason={onClickDeleteReason}
              waitCastItems={waitCastItems}
              setCertificateVisible={setCertificateVisible}
              setIsShowDeleteReason={setIsShowDeleteReason}
              recordData={recordData}
              onClickAddAttachmentList={onClickAddAttachmentList}
            />
          </TabPane>
        </Tabs>
      </main>
      <Button
        style={{ display: 'block', margin: 'auto' }}
        onClick={() => {
          navigate(-1)
        }}
      >
        返回
      </Button>
      <Modal
        visible={isShowDeleteReason}
        onOk={onClickDeleteReason}
        onCancel={() => {
          setIsShowDeleteReason(false)
        }}
      >
        <Form validateTrigger="onBlur" form={form} style={{ marginTop: 36 }}>
          <Form.Item name="deleteReason" label="删除原因">
            <Input />
          </Form.Item>
          {/* {isShowRemark && (
            <Form.Item name="whereaboutsRemark" label="备注">
              <TextArea placeholder="请输入备注" />
            </Form.Item>
          )} */}
        </Form>
      </Modal>
      <Modal
        visible={isShowClassificationModal}
        onOk={onClickSaveSetting}
        onCancel={() => {
          setIsShowClassificationModal(false)
        }}
      >
        <Form validateTrigger="onBlur" form={form} style={{ marginTop: 36 }}>
          <Form.Item name="classification" label="附件分类" initialValue="EXPLANATION">
            <Select>
              {[...AttachmentClassificationMap].map(([key, value], index) => (
                <Option key={index} value={key}>
                  {value}
                </Option>
              ))}
            </Select>
          </Form.Item>
          {/* {isShowRemark && (
            <Form.Item name="whereaboutsRemark" label="备注">
              <TextArea placeholder="请输入备注" />
            </Form.Item>
          )} */}
        </Form>
      </Modal>
      <Modal
        visible={isShowWechatUpload}
        onOk={onClickAssociatedPicture}
        onCancel={() => {
          setIsShowWechatUpload(false)
        }}
        width={700}
      >
        <>
          <div style={{ display: 'flex', alignItems: 'center', flex: 1, maxHeight: 800, overflow: 'auto' }}>
            {imgLists.map((item: any, index: number) => (
              <img
                onClick={() => onClickImg(index)}
                style={{
                  width: 300,
                  marginLeft: 20,
                  cursor: 'pointer',
                  border: selectMap.get(index) ? '3px solid red' : 'none'
                }}
                key={index}
                src={`data:image/png;base64,${item}`}
              />
            ))}
          </div>
        </>
      </Modal>
    </div>
  )
}

export default PropertyInvolved
